package com.local.controller.index;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.cloud.threads.UpDateCarOutInfoRunble;
import com.cloud.threads.UpLoadCarOutInfoRunble;
import com.cloud.threads.UploadPayBillRunble;
import com.cz073586.tools.util.Log4jUtil;
import com.cz073586.tools.util.ThreadPoolUtil;
import com.cz073586.tools.util.Tools;
import com.local.dao.mapers.CarParkInMapper;
import com.local.dao.mapers.CarParkOutMapper;
import com.local.manager.cfgManager.CloudConfigManager;
import com.local.model.CarParkIn;
import com.local.model.CarParkOut;
import com.local.model.LocalCarInRepertory;
import com.local.model.LocalCarType;
import com.local.model.LocalChargeBytime;
import com.local.model.LocalCoupon;
import com.local.model.LocalCouponCash;
import com.local.model.LocalPayBill;
import com.local.service.face.LocalCarInRepertoryService;
import com.local.service.face.LocalChargeByTimeCopyService;
import com.local.service.face.LocalCouponCashService;
import com.local.service.face.LocalCouponService;
import com.local.service.face.LogService;
import com.local.service.face.ParkwellCarOutService;
import com.local.service.face.ParkwellChargeBytimeService;
import com.local.service.face.ParkwellPayBillService;
import com.message.entity.PayInfo;
import com.other.controller.entity.LoginUser;
import com.other.controller.entity.ParkCarVo;
import com.other.controller.entity.ParkCarVoInfo;
import com.other.controller.entity.UserVO;
import com.qianhai.common.constants.CommonContans;
import com.qianhai.common.controller.BaseController;
import com.qianhai.common.exception.BaseException;
import com.qianhai.common.utils.UUIDGenerateUtil;

@RestController
@RequestMapping(value = "/parkOut", method = RequestMethod.POST)
public class CarParkOutController extends BaseController
{
	protected Log4jUtil log = Log4jUtil.getLog4j(this.getClass());
	
	@Autowired 
	private CarParkOutMapper carParkOutMapper;
	@Autowired
	private CarParkInMapper carParkInMapper;
	@Autowired
	private LogService logService;
	
	@Autowired
	private LogService logServier;
	
	@Autowired
	private ParkwellPayBillService payBill;
	
	@Autowired
	private LocalCouponCashService localCouponCashService;
	
	@Autowired
	private LocalCouponService localCouponService;
	
	@Autowired
	private ParkwellPayBillService parkwellPayBillService;
	
	@Autowired
	private ParkwellChargeBytimeService localChargeByTimeService;
	
	@Autowired
	private LocalCarInRepertoryService localCarInRepertoryService;
	
	
	public ParkCarVoInfo countCarNOMoney(ParkCarVo parkCarVo)
	{
		ParkCarVoInfo parkCarVoInfo = null;
		try{
			CarParkIn cpIn = payBill.selectCarNo(parkCarVo.getCarNo());
			if (!Tools.isEmpty(cpIn))
			{
				LocalCarType carType = new LocalCarType();
				// 小型车
				carType.setCartypeId("MIN_CAR");
				String carTypeUuid = payBill.queryCarType(carType).getCarTypeUuid();
				// 封装计费类
				LocalChargeBytime chargeBytime = new LocalChargeBytime();
				chargeBytime.setInTime(cpIn.getCreateTime());
				chargeBytime.setOutTime(new Date(System.currentTimeMillis()));
				chargeBytime.setCarType(carTypeUuid);
				
				
				//总停车费
				LocalCarInRepertory carInRepertory = localCarInRepertoryService.findCarInRepertoryByCarInUuid(cpIn.getUuid());
				//总停车费
				Double priceResult=localChargeByTimeService.queryCarinBillMoney(carInRepertory.getChargeUuid(),cpIn.getCreateTime(),new Date(System.currentTimeMillis()));
				/*double priceResult = servevice.queryBilling(chargeBytime,
						new ParkwellPayBillVo());*/
				
				//最新一条流水记录
				LocalPayBill lp=payBill.queryLastBill(cpIn.getUuid());
				if(!Tools.isEmpty(lp)&&!Tools.isEmpty(lp.getPayTime())){
					//最后一条支付时间
					Long lastPaTime=lp.getPayTime().getTime()+(15 *1000);
					//现在的时间
					Long now=new Date(System.currentTimeMillis()).getTime();
					if(lastPaTime>now){
						/*chargeBytime = new LocalChargeBytime();
						chargeBytime.setInTime(cpIn.getCreateTime());
						chargeBytime.setOutTime(lp.getPayTime());
						chargeBytime.setCarType(carTypeUuid);*/
						priceResult=localChargeByTimeService.queryCarinBillMoney(cpIn.getUuid(),cpIn.getCreateTime(),lp.getPayTime());
						/*priceResult = servevice.queryBilling(chargeBytime,
								new ParkwellPayBillVo());*/
					}
				}
				//已存在的流水集合
				List<LocalPayBill> listbillList = payBill.queryPayBillByCarNo(cpIn
						.getCarNo());
				
				// 返回抵用劵集合
				List<LocalCouponCash> li = localCouponCashService.queryCouponCashByCarNo(parkCarVo.getCarNo());
				
				// 返回流水装换集合
				List<PayInfo> payInfoLs = retParkwellPayBill(listbillList,li);
				
				//判断是否足够出场的金额
				Double pprice=new Double(priceResult);
				//统计已支付金额
				Double cashPrice=new Double(0d);
				if (!Tools.isEmpty(payInfoLs) && payInfoLs.size() > 0)
				{
					for (PayInfo bill : payInfoLs)
					{
						pprice -= bill.getPrice();
						cashPrice +=bill.getPrice();
					}
				}
				parkCarVoInfo = new ParkCarVoInfo();
				/*parkCarVoInfo.setStatus(!Tools.isEmpty(pprice) && pprice <= 0 ? "2"
						: "1");*/
				parkCarVoInfo.setCaroNo(parkCarVo.getCarNo());
				//停车总费用
				parkCarVoInfo.setPrice(priceResult*100);
				//还应该支付
				parkCarVoInfo.setPaid(cashPrice);
				parkCarVoInfo.setPayInfoLs(payInfoLs);
				parkCarVoInfo.setOrderId(cpIn.getUuid());
				return parkCarVoInfo;
			}
		}catch(Exception e)
		{
			// TODO: handle exception
			return null;
		}
		return parkCarVoInfo;
	}
	
	//统计已经支付的总钱
	public double retrunPayPrice(List<PayInfo> payInfoLs){
		double payPrice=0d;
		if(!Tools.isEmpty(payInfoLs)&&payInfoLs.size()>0){
			for(PayInfo pi:payInfoLs){
				payPrice +=!Tools.isEmpty(pi.getPrice())?pi.getPrice():0d;
			}
		}
		return payPrice;
	}
	
	public List<PayInfo> retParkwellPayBill(List<LocalPayBill> listbillList,List<LocalCouponCash> li)
	{
		try
		{
			List<PayInfo> payInfoLs = new ArrayList<PayInfo>();
			if (!Tools.isEmpty(listbillList) && listbillList.size() > 0)
			{
				for (LocalPayBill pb : listbillList)
				{
					// 流水表，装换payInfo
					PayInfo pi = new PayInfo();
					pi.setPayTime(!Tools.isEmpty(pb.getPayTime()) ? pb
							.getPayTime().getTime() : new Date(System
							.currentTimeMillis()).getTime());
					pi.setPayType(!Tools.isEmpty(pb.getPayType()) ? pb
							.getPayType() : "其他");
					pi.setPrice(!Tools.isEmpty(pb.getActualPrice()) ? (int)(pb.getActualPrice()*100) : !Tools.isEmpty(pb.getPrice())?(int)(pb.getPrice()*100):0);
					
					List<LocalCoupon> pCouponLs = localCouponService
							.queryByBillUuid(pb.getPayBillUuid());
					if (!Tools.isEmpty(pCouponLs))
					{
						for (LocalCoupon pc : pCouponLs)
						{
							PayInfo pic = new PayInfo();
							pic.setPayTime(!Tools.isEmpty(pc.getPayTime()) ? pc
									.getPayTime().getTime() : new Date(System
									.currentTimeMillis()).getTime());
							pic.setPayType("优惠券");
							pic.setPrice(!Tools.isEmpty(pc.getCouponPrice()) ? (int)(pc
									.getCouponPrice()*100) : 0);
							payInfoLs.add(pic);
						}
					}
					payInfoLs.add(pi);
				}
				
			}
			if (!Tools.isEmpty(li))
			{
				for (LocalCouponCash pcCash : li)
				{
					PayInfo payInfo = new PayInfo();
					payInfo.setPayTime(new Date(System.currentTimeMillis()).getTime());
					payInfo.setPayType(!Tools.isEmpty(pcCash.getArrtr1())?pcCash.getArrtr1():"抵用劵");
					payInfo.setPrice(!Tools.isEmpty(pcCash.getPrice()) ? (int)(pcCash.getPrice()*100) : 0);
					payInfoLs.add(payInfo);
				}
			}
			return payInfoLs;
			
		} catch (Exception e)
		{
			// TODO: handle exception
			return null;
		}
	}
	
	@RequestMapping(value = "/parkOut.action", consumes = "application/json", produces = "application/json")
	@ResponseBody
	public ModelMap parkOut(
			@RequestBody com.other.controller.entity.CarParkOut carParkOut,
			HttpServletRequest request)
	{
		ModelMap resultMap = new ModelMap();
		try
		{
			//出场时，保存出场纪录，状态为待出场1：，上传到云
			CarParkOut carOut=saveCarParkOut(carParkOut);
			if(!Tools.isEmpty(carOut)){
				if (CloudConfigManager.instance().isOpen())
				{
					UpLoadCarOutInfoRunble upload = new UpLoadCarOutInfoRunble(
							carOut, logService);
					ThreadPoolUtil.instance().execute(upload);
				}
			}
			
			//出场的现金信息，carParkOut 转换为 localPayBill表，然后添加本地流水，并上传到云
			LocalPayBill linebill=parkwellPayBillService.addOtherPayBill(returnLocalPayBill(carParkOut));
			
			if(!Tools.isEmpty(linebill)){
				//上传流水
				if (CloudConfigManager.instance().isOpen())
				{
					UploadPayBillRunble payBillload = new UploadPayBillRunble(
							linebill,logService);
					ThreadPoolUtil.instance().execute(payBillload);
				}
			}
			
			//查询出场纪录，更新出场状态
			CarParkOut cc=carParkOutMapper.selectCarNo(carParkOut.getCarNo());
			cc.setStatus(0);
			Integer updd=carParkOutMapper.updateByPrimaryKeySelective(cc);
			
			if(!Tools.isEmpty(updd)&&updd>0){
				//更新出场纪录，并删除本地纪录
				if (CloudConfigManager.instance().isOpen())
				{
					UpDateCarOutInfoRunble upload = new UpDateCarOutInfoRunble(
							cc,logServier);
					ThreadPoolUtil.instance().execute(upload);
				}
			}

			resultMap.put(CommonContans.STRUTS_RESULT,
					CommonContans.STRUTS_SUCCESS);
		} catch (Throwable e)
		{
			// 请保持所有代码一直性，没有特殊处理请使用该代码.
			this.printExction(resultMap, e);
		}
		return resultMap;
	}
	
	public LocalPayBill returnLocalPayBill(com.other.controller.entity.CarParkOut carParkOut){
		LocalPayBill parkwellPayBill = new LocalPayBill();
		try
		{
			CarParkIn carIn=new CarParkIn();
			carIn=carParkInMapper.selectCarNo(carParkOut.getCarNo());
			
			parkwellPayBill.setPayTime(!Tools.isEmpty(carParkOut.getOpTime())?carParkOut.getOpTime():new Date(System.currentTimeMillis()));
			parkwellPayBill.setCarNo(!Tools.isEmpty(carParkOut.getCarNo())?carParkOut.getCarNo():"无");
			parkwellPayBill.setPayType("现金");
			parkwellPayBill.setPrice(!Tools.isEmpty(carParkOut.getPrice())?carParkOut.getPrice()/100:0d);
			parkwellPayBill.setParkInUuid(!Tools.isEmpty(carIn)?carIn.getUuid():null);
			
			parkwellPayBill.setActualPrice(!Tools.isEmpty(carParkOut.getPaid())?carParkOut.getPaid()/100:
				!Tools.isEmpty(carParkOut.getPrice())?carParkOut.getPrice()/100:0d);
			
			parkwellPayBill.setCarinCreatAt(!Tools.isEmpty(carParkOut.getCarinCreatAt())?carParkOut.getCarinCreatAt():new Date());
			parkwellPayBill.setCaroutCareteAt(!Tools.isEmpty(carParkOut.getCaroutCareteAt())?carParkOut.getCaroutCareteAt():new Date());
		} catch (Throwable e)
		{
			throw new BaseException(e.getMessage());
		}
		return parkwellPayBill;
	}
	
	public CarParkOut returnCarParkOut(
			com.other.controller.entity.CarParkOut carParkOut)
	{
		CarParkOut cc = new CarParkOut();
		cc.setUuid(UUIDGenerateUtil.generate());
		cc.setCarNo(carParkOut.getCarNo());
		cc.setCreateTime(new Date(System.currentTimeMillis()));
		cc.setPic1(carParkOut.getPic_1());
		cc.setPic2(carParkOut.getPic_2());
		String exchanuui = CloudConfigManager.instance().getCfgValueByKey(
				"exchange_id");
		cc.setExchangeUuid(exchanuui);
		cc.setRecordId(UUIDGenerateUtil.generate());
		cc.setEquipment(carParkOut.getDeviceNo());
		cc.setOpenTime(carParkOut.getCarOutTime());
		cc.setStatus(0);
		return cc;
	}
	
	public CarParkOut saveCarParkOut(com.other.controller.entity.CarParkOut carParkOut){
		// 如果不上报车牌
		if (Tools.isEmpty(carParkOut.getCarNo())
				&& !Tools.isEmpty(carParkOut.getPic_1()))
		{
			
			String carNo = carParkOut.getPic_1().substring(
					carParkOut.getPic_1().lastIndexOf("_") + 1,
					carParkOut.getPic_1().lastIndexOf("."));
			
			carParkOut.setCarNo(carNo);
		}
		if("".equals(carParkOut.getCarNo()))
		{
			carParkOut.setCarNo("无效车牌");
		}
		
		CarParkOut carOut=new CarParkOut();
		carOut.setPic1(!Tools.isEmpty(carParkOut.getPic_1())?carParkOut.getPic_1():null);
		carOut.setPic2(!Tools.isEmpty(carParkOut.getPic_2())?carParkOut.getPic_2():null);
		carOut.setCarNo(carParkOut.getCarNo());
		carOut.setUuid(UUIDGenerateUtil.generate());
		
		//查看进场纪录，赋予进场ID
		CarParkIn carIn=carParkInMapper.selectCarNo(carParkOut.getCarNo());
		carOut.setCarInUuid(!Tools.isEmpty(carIn)?carIn.getUuid():null);
		
		//状态，待出场
		carOut.setStatus(1);
		carOut.setEquipment(!Tools.isEmpty(carParkOut.getDeviceNo())?carParkOut.getDeviceNo():null);
		String exchanuui = CloudConfigManager.instance().getCfgValueByKey("exchange_id");
		carOut.setExchangeUuid(!Tools.isEmpty(exchanuui)?exchanuui:null);
		carOut.setCreateTime(new Date());
		SimpleDateFormat dd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		carOut.setOpenTime(dd.format(carOut.getCreateTime()));
		
		Integer upd=carParkOutMapper.insertSelective(carOut);
		
		return carOut;
	}
	
	
	@RequestMapping(value = "/login.action", consumes = "application/json", produces = "application/json")
	@ResponseBody
	public ModelMap login(@RequestBody LoginUser loginUser)
	{
		ModelMap resultMap = new ModelMap();
		try
		{
			
			UserVO user = new UserVO();
			user.setToken(UUIDGenerateUtil.generate());
			
			resultMap.put(CommonContans.STRUTS_DATA, user);
			resultMap.put(CommonContans.STRUTS_RESULT,
					CommonContans.STRUTS_SUCCESS);
		} catch (Throwable e)
		{
			this.printExction(resultMap, new BaseException("20000-00001"));
		}
		return resultMap;
	}
	
}
